package com.project.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.project.entity.OrderInfo;
import com.project.entity.Product;
import com.project.service.OrderInfoService;
import com.project.util.StringUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.redisson.api.RLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

@RestController
@Api(tags = "采购信息查询")
@RequestMapping("/orderInfo")
public class OrderInfoController {
    @Autowired
    public OrderInfoService orderInfoService;

    @Autowired
    RedisTemplate<String, Object> redisTemplate;
    @Autowired
    public RLock rLock;

    @ApiOperation(value = "动态分页查询")
    @GetMapping("cutByItem")
    public IPage<OrderInfo> cutByItem(Integer pageNo, String factoryName, String startDate, String endDate) {
        return orderInfoService.cutByItem(pageNo, factoryName, startDate, endDate);
    }

//    @ApiOperation(value = "查看采购详情")
//    @GetMapping("findById/{id}")
//    public List<Product> findById(@PathVariable("id") Integer orderId){
//      return   orderInfoService.findById(orderId);
//    }

    @ApiOperation(value = "查看采购详情")
    @GetMapping("findById/{orderId}")
    public List<Product> findById(@PathVariable("orderId") Integer orderId) throws InterruptedException {
        String key = String.valueOf(orderId);
        List<Product> productList = null;
        if (redisTemplate.hasKey(key)) {
            //存在缓存
            ValueOperations<String, Object> operations = redisTemplate.opsForValue();
            String json = (String) operations.get(key);
            productList = JSONObject.parseArray(json, Product.class);

        } else {
            //竞争锁
            boolean bl = rLock.tryLock(0, 10, TimeUnit.SECONDS);
            if (bl) {
                //不存在缓存
                  productList = orderInfoService.findById(orderId);
                //防止缓存雪崩
                long keyNum = key.hashCode();
                //获取随机数，0-最大值之间
                int time = (int) (keyNum % StringUtil.CACHE_TIME_MIN);
                if (time < StringUtil.CACHE_TIME_MIN) {
                    time = StringUtil.CACHE_TIME_MIN;
                }
                  //判断数据库是否有数据库
                if (productList.size() == 0) {
                    //数据库为null对象，缓存时间变短
                    redisTemplate.opsForValue().set(key, JSON.toJSONString(productList), StringUtil.CACHE_TIME_MIN, TimeUnit.SECONDS);
                } else {
                    redisTemplate.opsForValue().set(key, JSON.toJSONString(productList), time, TimeUnit.SECONDS);
                   return productList;
                }
                //释放锁
                rLock.unlock();
            }else {
                //没有拿到锁
                Thread.sleep(500);  //休眠等待500毫秒
             this.orderInfoService.findById(orderId);  //查询，重新竞争锁
            }
        }
        return productList;
    }


}
